import { baseUrl } from './config.js';
import used from './used.js';
//域名
//请求 - 这是真请求
function http(opts, token) {
	let isLoading = opts.params.rLoading ? true : false;
	let thisBaseUrl = baseUrl;
	let httpDefaultOpts = {
		url: thisBaseUrl + opts.url,
		data: opts.params,
		method: opts.method,
		timeout: 20000,
		sslVerify: false,
		header: opts.method == 'GET' ? {
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			'content-Type': 'application/x-www-form-urlencoded'
		} : {
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		},
		dataType: 'json',
	}
	//是否带token
	if (token) {
		httpDefaultOpts.header.token = token;
	}
	//删除rLoading
	delete opts.params.rLoading;
	//promise
	let promise = new Promise(function (resolve, reject) {
		let network; //网络状态
		if (isLoading) {
			used.msgLoading();
		}
		//网络状态
		uni.getNetworkType({
			success: function (res) {
				network = res.networkType;
				if (res.networkType == 'none') {
					uni.showToast({
						title: '无网络',
						icon: 'none',
						duration: 5000
					});
				}
			}
		});
		uni.request(httpDefaultOpts).then(
			(res) => {
				//成功
				if (res[1]) {
					if (isLoading) {
						uni.hideLoading();
					}
					//成功
					if (res[1].statusCode == 200) {
						//登录失效 token失效，请重新登录
						if (res[1].data.code == 401) {
							console.log('登录失效 token失效，请重新登录');
							used.noTokenGo();
						} else {
							//返回参数
							resolve(res[1].data);
						}
					} else if (res[1].statusCode == 401) {
						used.noTokenGo();
					} else {
						//失败
						used.msg('服务器繁忙，请重试!');
						resolve(res[1].data)
					}
				} else {
					//失败
					used.msg("网络异常,请重试",);
				}
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
}
//请求 - 不带token
const httpRequest = (opts) => {
	opts.params = opts.params ? opts.params : {};
	if (opts.params.token) {
		return http(opts, opts.params.token);
	} else {
		return http(opts);
	}
};
//请求 - 带Token
const httpTokenRequest = (opts) => {
	let token = uni.getStorageSync('token');
	opts.params = opts.params ? opts.params : {};
	return http(opts, token);
};
//图片上传
const httpUpload = (url, img) => {
	var token = uni.getStorageSync("token");
	if (!token) {
		uni.hideLoading()
		return false;
	}

	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseUrl + url,
			filePath: img,
			name: 'file',
			header: {},
			formData: {
				'token': token
			},
			success: (uploadFileRes) => {
				resolve(JSON.parse(uploadFileRes.data))
			},
			fail: (err) => {
				reject(err)
			},
			complete() {
				uni.hideLoading()
			}
		});
	})
};

export {
	httpRequest,
	httpTokenRequest,
	httpUpload
}
